const path = require("path");
const fs = require("fs");

const multer = require("koa-multer");
//上传不同类型的图片，如：头像，封面，博客内容的图片
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const date = new Date();
    const curmon = date.getMonth() + 1,
      curday = date.getDate();

    //根据时间戳创建文件夹
    if (!fs.existsSync(`./upload/${curmon}`)) {
      fs.mkdirSync(`./upload/${curmon}`);
    } else {
      if (!fs.existsSync(`./upload/${curmon}/${curday}`)) {
        fs.mkdirSync(`./upload/${curmon}/${curday}`);
      }
    }
    //文件名字要有文件的路径，在访问时才能根据文件名访问
    cb(null, `./upload/${curmon}/${curday}`);
  },
  filename: (req, file, cb) => {
    const date = new Date();
    const curmon = date.getMonth() + 1,
      curday = date.getDate();
    cb(
      null,
      curmon + "&" + curday + "&" + Date.now() + path.extname(file.originalname)
    );
  },
});
const picupload = multer({
  storage,
});
module.exports = {
  picupload: picupload.single("picture"),
};
